home *** CD-ROM | disk | FTP | other *** search
/ Visual Cafe 3 / Visual Cafe 3.ISO / Vcafe / Sample.bin / DitherTest.java < prev    next >
Text File  |  1998-09-15  |  9KB  |  347 lines

  1. /*
  2.  * @(#)DitherTest.java    1.5 98/03/23
  3.  *
  4.  * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
  7.  * modify and redistribute this software in source and binary code form,
  8.  * provided that i) this copyright notice and license appear on all copies of
  9.  * the software; and ii) Licensee does not utilize the software in a manner
  10.  * which is disparaging to Sun.
  11.  *
  12.  * This software is provided "AS IS," without a warranty of any kind. ALL
  13.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
  14.  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
  15.  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
  16.  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
  17.  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
  18.  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
  19.  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
  20.  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
  21.  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
  22.  * POSSIBILITY OF SUCH DAMAGES.
  23.  *
  24.  * This software is not designed or intended for use in on-line control of
  25.  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
  26.  * the design, construction, operation or maintenance of any nuclear
  27.  * facility. Licensee represents and warrants that it will not use or
  28.  * redistribute the Software for such purposes.
  29.  */
  30.  
  31. import java.applet.Applet;
  32. import java.awt.event.*;
  33. import java.awt.*;
  34. import java.awt.image.ColorModel;
  35. import java.awt.image.MemoryImageSource;
  36. import java.lang.InterruptedException;
  37.  
  38. public class DitherTest extends Applet implements Runnable {
  39.     final static int NOOP = 0;
  40.     final static int RED = 1;
  41.     final static int GREEN = 2;
  42.     final static int BLUE = 3;
  43.     final static int ALPHA = 4;
  44.     final static int SATURATION = 5;
  45.  
  46.     ThreadGroup appletThreadGroup;
  47.     Thread runner;
  48.  
  49.     DitherControls XControls;
  50.     DitherControls YControls;
  51.     DitherCanvas canvas;
  52.  
  53.     public void init() {
  54.     String xspec, yspec;
  55.     int xvals[] = new int[2];
  56.     int yvals[] = new int[2];
  57.  
  58.     try {
  59.         xspec = getParameter("xaxis");
  60.     } catch (Exception e) {
  61.         xspec = null;
  62.     }
  63.     try {
  64.         yspec = getParameter("yaxis");
  65.     } catch (Exception e) {
  66.         yspec = null;
  67.     }
  68.     if (xspec == null) xspec = "red";
  69.     if (yspec == null) yspec = "blue";
  70.     int xmethod = colormethod(xspec, xvals);
  71.     int ymethod = colormethod(yspec, yvals);
  72.  
  73.     setLayout(new BorderLayout());
  74.     XControls = new DitherControls(this, xvals[0], xvals[1],
  75.                        xmethod, false);
  76.     YControls = new DitherControls(this, yvals[0], yvals[1],
  77.                        ymethod, true);
  78.     YControls.addRenderButton();
  79.     add("North", XControls);
  80.     add("South", YControls);
  81.     add("Center", canvas = new DitherCanvas());
  82.  
  83.     appletThreadGroup = Thread.currentThread().getThreadGroup();
  84.     }
  85.  
  86.     public void destroy() {
  87.         remove(XControls);
  88.         remove(YControls);
  89.         remove(canvas);
  90.     }
  91.  
  92.     public void start() {
  93.         runner = new Thread(this);
  94.     runner.start();
  95.     }
  96.  
  97.     public void stop() {
  98.     runner = null;
  99.     }
  100.  
  101.     public static void main(String args[]) {
  102.     Frame f = new Frame("DitherTest");
  103.     DitherTest    ditherTest = new DitherTest();
  104.  
  105.     ditherTest.init();
  106.  
  107.     f.add("Center", ditherTest);
  108.     f.pack();
  109.     f.show();
  110.  
  111.     ditherTest.start();
  112.     }
  113.  
  114.     int colormethod(String s, int vals[]) {
  115.     int method = NOOP;
  116.  
  117.     if (s == null)
  118.         s = "";
  119.  
  120.     String lower = s.toLowerCase();
  121.     int len = 0;
  122.     if (lower.startsWith("red")) {
  123.         method = RED;
  124.         lower = lower.substring(3);
  125.     } else if (lower.startsWith("green")) {
  126.         method = GREEN;
  127.         lower = lower.substring(5);
  128.     } else if (lower.startsWith("blue")) {
  129.         method = BLUE;
  130.         lower = lower.substring(4);
  131.     } else if (lower.startsWith("alpha")) {
  132.         method = ALPHA;
  133.         lower = lower.substring(4);
  134.     } else if (lower.startsWith("saturation")) {
  135.         method = SATURATION;
  136.         lower = lower.substring(10);
  137.     }
  138.  
  139.     if (method == NOOP) {
  140.         vals[0] = 0;
  141.         vals[1] = 0;
  142.         return method;
  143.     }
  144.  
  145.     int begval = 0;
  146.     int endval = 255;
  147.  
  148.     try {
  149.         int dash = lower.indexOf('-');
  150.         if (dash < 0) {
  151.         begval = endval = Integer.parseInt(lower);
  152.         } else {
  153.         begval = Integer.parseInt(lower.substring(0, dash));
  154.         endval = Integer.parseInt(lower.substring(dash+1));
  155.         }
  156.     } catch (Exception e) {
  157.     }
  158.  
  159.     if (begval < 0) begval = 0;
  160.     if (endval < 0) endval = 0;
  161.     if (begval > 255) begval = 255;
  162.     if (endval > 255) endval = 255;
  163.  
  164.     vals[0] = begval;
  165.     vals[1] = endval;
  166.  
  167.     return method;
  168.     }
  169.  
  170.     void applymethod(int c[], int method, int step, int total, int vals[]) {
  171.     if (method == NOOP)
  172.         return;
  173.     int val = ((total < 2)
  174.            ? vals[0]
  175.            : vals[0] + ((vals[1] - vals[0]) * step / (total - 1)));
  176.     switch (method) {
  177.     case RED:
  178.         c[0] = val;
  179.         break;
  180.     case GREEN:
  181.         c[1] = val;
  182.         break;
  183.     case BLUE:
  184.         c[2] = val;
  185.         break;
  186.     case ALPHA:
  187.         c[3] = val;
  188.         break;
  189.     case SATURATION:
  190.         int max = Math.max(Math.max(c[0], c[1]), c[2]);
  191.         int min = max * (255 - val) / 255;
  192.         if (c[0] == 0) c[0] = min;
  193.         if (c[1] == 0) c[1] = min;
  194.         if (c[2] == 0) c[2] = min;
  195.         break;
  196.     }
  197.     }
  198.  
  199.     public void run() {
  200.         canvas.setImage(null);    // Wipe previous image
  201.         Image img = calculateImage();
  202.         synchronized(this) {
  203.             if (img != null && runner == Thread.currentThread())
  204.                 canvas.setImage(img);
  205.         }
  206.     }
  207.   
  208.     /**
  209.      * Calculates and returns the image.  Halts the calculation and returns
  210.      * null if the Applet is stopped during the calculation.
  211.      */
  212.     Image calculateImage() {
  213.         Thread me = Thread.currentThread();
  214.  
  215.         int width = canvas.getSize().width;
  216.     int height = canvas.getSize().height;
  217.     int xvals[] = new int[2];
  218.     int yvals[] = new int[2];
  219.     int xmethod = XControls.getParams(xvals);
  220.     int ymethod = YControls.getParams(yvals);
  221.     int pixels[] = new int[width * height];
  222.     int c[] = new int[4];
  223.     int index = 0;
  224.     for (int j = 0; j < height; j++) {
  225.         for (int i = 0; i < width; i++) {
  226.         c[0] = c[1] = c[2] = 0;
  227.         c[3] = 255;
  228.         if (xmethod < ymethod) {
  229.             applymethod(c, xmethod, i, width, xvals);
  230.             applymethod(c, ymethod, j, height, yvals);
  231.         } else {
  232.             applymethod(c, ymethod, j, height, yvals);
  233.             applymethod(c, xmethod, i, width, xvals);
  234.         }
  235.         pixels[index++] = ((c[3] << 24) |
  236.                    (c[0] << 16) |
  237.                    (c[1] << 8) |
  238.                    (c[2] << 0));
  239.         }
  240.  
  241.             // Poll once per row to see if we've been told to stop.
  242.             if (runner != me)
  243.                 return null;
  244.     }
  245.  
  246.         return createImage(new MemoryImageSource(width, height,
  247.               ColorModel.getRGBdefault(), pixels, 0, width));
  248.     }
  249.  
  250.     public String getAppletInfo() {
  251.         return "An interactive demonstration of dithering.";
  252.     }
  253.   
  254.     public String[][] getParameterInfo() {
  255.         String[][] info = {
  256.             {"xaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}", "The color of the Y axis.  Default is RED."}, 
  257.             {"yaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}", "The color of the X axis.  Default is BLUE."}
  258.         };
  259.         return info;
  260.     }
  261. }
  262.  
  263. class DitherCanvas extends Canvas {
  264.     Image img;
  265.     static String calcString = "Calculating...";
  266.  
  267.     public void paint(Graphics g) {
  268.     int w = getSize().width;
  269.     int h = getSize().height;
  270.     if (img == null) {
  271.         super.paint(g);
  272.         g.setColor(Color.black);
  273.         FontMetrics fm = g.getFontMetrics();
  274.         int x = (w - fm.stringWidth(calcString))/2;
  275.         int y = h/2;
  276.         g.drawString(calcString, x, y);
  277.     } else {
  278.             g.drawImage(img, 0, 0, w, h, this);
  279.         }
  280.     }
  281.  
  282.     public void update(Graphics g) {
  283.     paint(g);
  284.     }
  285.  
  286.     public Dimension getMinimumSize() {
  287.     return new Dimension(20, 20);
  288.     }
  289.  
  290.     public Dimension getPreferredSize() {
  291.     return new Dimension(200, 200);
  292.     }
  293.  
  294.     public Image getImage() {
  295.     return img;
  296.     }
  297.  
  298.     public void setImage(Image img) {
  299.     this.img = img;
  300.         paint(getGraphics());
  301.     }
  302. }
  303.  
  304. class DitherControls extends Panel implements ActionListener {
  305.     TextField start;
  306.     TextField end;
  307.     Button button;
  308.     Choice choice;
  309.     DitherTest applet;
  310.  
  311.     static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER, 10, 5);
  312.  
  313.     public DitherControls(DitherTest app, int s, int e, int type,
  314.               boolean vertical) {
  315.     applet = app;
  316.     setLayout(dcLayout);
  317.     add(new Label(vertical ? "Vertical" : "Horizontal"));
  318.     add(choice = new Choice());
  319.     choice.addItem("Noop");
  320.     choice.addItem("Red");
  321.     choice.addItem("Green");
  322.     choice.addItem("Blue");
  323.     choice.addItem("Alpha");
  324.     choice.addItem("Saturation");
  325.     choice.select(type);
  326.     add(start = new TextField(Integer.toString(s), 4));
  327.     add(end = new TextField(Integer.toString(e), 4));
  328.     }
  329.  
  330.     public void addRenderButton() {
  331.     add(button = new Button("New Image"));
  332.     button.addActionListener(this);
  333.     }
  334.  
  335.     public int getParams(int vals[]) {
  336.     vals[0] = Integer.parseInt(start.getText());
  337.     vals[1] = Integer.parseInt(end.getText());
  338.     return choice.getSelectedIndex();
  339.     }
  340.  
  341.     public void actionPerformed(ActionEvent e) {
  342.         if (e.getSource() == button) {
  343.             applet.start();
  344.         }
  345.     }
  346. }
  347.